package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"shuqi-novel/models/cache"
	"shuqi-novel/models/mysql"
	"time"

	"shuqi-novel/userrpc/internal/svc"
	"shuqi-novel/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookListLogic {
	return &BookListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 小说列表
func (l *BookListLogic) BookList(in *userrpc.BookListRequest) (*userrpc.BookListResponse, error) {
	// todo: add your logic here and delete this line

	var list []*userrpc.BookList

	key := fmt.Sprintf("bookList_%s", in)
	cacheData, _ := cache.Rdb.Get(l.ctx, key).Result()
	if cacheData == "" {
		list = mysql.BookList(mysql.DB, in)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, key, jsonData, time.Minute*10)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	return &userrpc.BookListResponse{
		List: list,
	}, nil
}
